<template>
  <view class="login-page">
    <view class="banner-block">
      <image :src="loginImgObj.loginbg" mode="widthFix"></image>
    </view>
    <view class="login-main">
      <view class="logo">
        <image :src="loginImgObj.logobg" mode="widthFix"></image>
      </view>
      <form class="login-form" name="loginForm">
        <view class="form-item user-area">
          <view class="form-label">
            <image :src="loginImgObj.userbg" mode="widthFix"></image>
            <text class="form-label-text">{{ loginMethod }}</text>
          </view>
          <view class="form-item-content">
            <input name="user" type="text" v-model="loginForm.username" autocomplete="off" maxlength="20"
              @blur="handleUsername" :placeholder="`请输入${loginMethod}`" />

            <view class="suffix" v-if="loginForm.username">
              <image :src="loginImgObj.closebg" @click="clearphone" class="close-icon" mode="widthFix"></image>
            </view>
          </view>
          <text v-show="valid.username" class="error">{{ valid.username }}</text>
        </view>
        <view class="form-item pwd-area">
          <view class="form-label">
            <image :src="loginImgObj.passwordbg" mode="widthFix"></image>
            <text class="form-label-text">密码</text>
          </view>
          <view class="form-item-content">
            <input name="pwd" v-if="showPwd" v-model="loginForm.pwd" type="text" autocomplete="new-password"
              placeholder="请输入密码" @blur="handlePwd" />
            <input name="pwd" v-if="!showPwd" v-model="loginForm.pwd" password type="password"
              autocomplete="new-password" placeholder="请输入密码" @blur="handlePwd" />
            <view class="suffix">
              <u-icon v-if="!showPwd" @click="showPwd = !showPwd" name="eye-off"></u-icon>
              <u-icon v-if="showPwd" @click="showPwd = !showPwd" name="eye-fill"></u-icon>
            </view>
          </view>
          <text v-show="valid.pwd" class="error">{{ valid.pwd }}</text>
        </view>
        <view class="options-row">
          <view class="remember-item">
            <uni-icons @click="rememberPassword = !rememberPassword" v-if="!rememberPassword" type="circle"
              size="24"></uni-icons>
            <uni-icons color="#409EFF" v-if="rememberPassword" @click="rememberPassword = !rememberPassword"
              type="checkbox" size="20"></uni-icons>
            <text :style="{ color: rememberPassword ? textColor : '#333' }">记住密码</text>
          </view>
          <view class="remember-item">
            <u-link text="忘记密码?" color="#333" :underline="false" @click="forgotPwdClick"></u-link>
          </view>

        </view>
        <view class="login-btn">
          <button class="syswin-button primary" :class="{ 'disabled': isLoading }" :disabled="isLoading"
            @click="loginSubmit">{{ isLoading ? '登录中...' : '进入' }}</button>
        </view>
      </form>

    </view>

    <!-- <SendCode v-if="configValueStatus" :visible="configValueStatus" :phone="phone" @colse="sendCodeClose" @success="sendCodeSuc"></SendCode> -->

    <view class="wuyetoon-agreement">
      <uni-icons @click="isAgree = !isAgree" v-if="!isAgree" type="circle" size="16"></uni-icons>
      <uni-icons color="#409EFF" v-if="isAgree" @click="isAgree = !isAgree" type="checkbox" size="20"></uni-icons>
      <text>我已同意并阅读</text>
      <text class="agreement-text" @click="seeAggrement()">物业通用户协议</text>
    </view>
    <view class="version">Ver{{ version }}</view>
    <agreement v-if="isShowAgreement" :showtext="isShowAgreement" @close="isShowAgreement = false" />
  </view>
</template>

<script>
import agreement from './agreement.vue'
// import { changeBaseURL, getBaseURL } from '@/config/serve.js'
// import createRequest from '@/utils/request'
// import singleCheck from '@/pages/components/single-check.vue'
// import SendCode from './sendCode.vue'
import CryptoJS from '@/utils/cryptojs/crypto-js.js'

import { encryptPwd, decrypt, decryptnew } from '@/utils/parseData'
// import createAxios from ''

const secretKey = "wytfw3JtZXJyZWZvcm1lc4";

export default {
  name: 'login',
  components: {
    agreement,
    // SendCode,
    // singleCheck
  },
  data() {
    return {
      phone: '',
      loginForm: {
        username: '',
        pwd: '',
        server: 'https://218.13.4.206:7571', // 服务器IP地址
        code: ''
      },
      loginImgObj: {
        loginbg: `${this.$baseIMGUrl}/static/assets/img/login/login-bg.png`,
        logobg: `${this.$baseIMGUrl}/static/assets/img/login/logo.png`,
        userbg: `${this.$baseIMGUrl}/static/assets/img/login/user.png`,
        closebg: `${this.$baseIMGUrl}/static/assets/img/login/close.png`,
        passwordbg: `${this.$baseIMGUrl}/static/assets/img/login/password.png`,
      },
      inputType: 'password',
      textColor: '#409EFf',
      valid: {
        username: '',
        pwd: ''
      },
      loginMethodObj: {
        '0': '手机号',
        '1': '/工号',
        '2': '/账号'
      },
      loginMethod: '手机号/工号/账号',
      configValueStatus: false,
      isCheckSendCode: false,
      configValue: false, // 短信验证
      isSendCode: false, // 是否已经发送验证码
      btnText: '获取验证码',
      codeInterval: null,
      isAgree: false, // 是否同意
      isShowAgreement: false, // 是否显示协议
      mode: 1, // 1为验证码登录, 2为密码登录
      showPwd: false,
      isLoading: false,
      rememberPassword: false,
      passwordShow: 1,
      isMultipleOrgUser: false,
    }
  },
  watch: {
    rememberPassword(newVal) {
      this.textColor = newVal ? '#409EFf' : '#000'
    },
  },
  computed: {
    isPasswordMode() {
      return this.mode === 0
    },
    version() {
      // 小程序环境获取版本号
      return '7.6.0' // 小程序可在manifest.json中配置版本号后读取


    },
    isValid() {
      if (!this.isAgree) {
        return false
      }
      if (this.validUsername(this.loginForm.username) || this.validPwd(this.loginForm.pwd)) {
        return false
      }
      return true
    },

  },
  onLoad() {

    // const token = uni.getStorageSync('XUserToken');
    // if (token) {
    //   // 已登录，直接跳首页
    //   uni.switchTab({ url: '/pages/home/index' });
    // }

    this.__getInfoCode()
    this.initState()
    // const loginForm = this.$store.state.workbench.loginForm
    // const loginForm = {}
    // if(loginForm) {
    //   this.loginForm.username = loginForm.username
    //   this.isAgree = loginForm.isAgree
    //   this.$store.commit('setLoginForm', null)
    // }
  },
  methods: {
    validUsername(username) {
      if (!username) {
        return `${this.loginMethod}不能为空`
      }
      return ''
    },
    validPwd(pwd) {
      if (pwd.length >= 1) {
        return ''
      } else {
        return '请输入密码,不小于1位'
      }
    },
    handleUsername() {
      this.valid.username = this.validUsername(this.loginForm.username)
    },
    handlePwd() {
      this.valid.pwd = this.validPwd(this.loginForm.pwd)
    },
    initState() {
      let res = uni.getStorageSync('userName')
      if (res) {
        this.loginForm.username = res
        this.isAgree = true
      }
      // let server = uni.getStorageSync('serverIpPort')
      // if (server) {
      //   this.loginForm.server = server
      // }
      // let oldRememberPwd = uni.getStorageSync('userPassword')
      // if (oldRememberPwd) {
      //   let encrypted = CryptoJS.AES.encrypt(oldRememberPwd, secretKey).toString()
      //   uni.setStorageSync('localRemember', encrypted)
      //   uni.removeStorageSync('userPassword')
      // }
      let rememberPassword = uni.getStorageSync('rememberpwd')
      if (rememberPassword) {
        this.isAgree = true;
        this.rememberPassword = true;
        let pwd = uni.getStorageSync('password')
        if (pwd) {

          // let bytes = CryptoJS.AES.decrypt(pwd, secretKey)
          // let decrypted = decryptnew(pwd)
          // console.log(decrypted, '解密的密码')

          // if (decrypted) {
          this.loginForm.pwd = pwd
          // }
        }
      } else {
        uni.setStorageSync('rememberpwd', this.rememberPassword.toString())
      }
    },
    clearphone() {
      console.log('clearphone')
      this.loginForm.username = ''
    },
    async getCode() {
      if (this.isSendCode) {
        return
      }

      if (!this.loginForm.username) {
        uni.showToast({ title: '请输入手机号/工号/账号', icon: 'none' })
        return
      }

      this.isSendCode = true
      let time = 59
      this.btnText = '60s'

      this.codeInterval = setInterval(() => {
        this.btnText = time + 's'
        time -= 1
        if (time < 0) {
          clearInterval(this.codeInterval)
          this.btnText = '获取验证码'
          this.isSendCode = false
        }
      }, 1000)

      let res = await this.$Geting(`/workbench/admin/getCode`, {
        phone: this.loginForm.username
      })
      if (res.code === '0') {
        this.loginForm.code = res.data
      } else {
        uni.showToast({ title: res.message, icon: 'none' })
      }
    },
    __getInfoCode() {
      let baseUrl = this.$baseUrl
      if (!baseUrl) return

      this.$Geting(this.$api.commonConfigList).then(res => {
        if (res && res.isSuccess) {
          let d = res.data
          d.forEach(e => {
            if (e.configName == '短信双重验证') {
              this.configValue = e.configValue == 1
            }
            if (e.configName === '忘记密码是否显示') {
              this.passwordShow = +e.configValue[1]
            }
            if (e.configName === '登录方式') {
              if (e.configValue) {
                let arr = e.configValue ? e.configValue.split(',') : ['0'],
                  str = '手机号'
                arr.forEach(item => {
                  if (item === '1') {
                    str += '/工号'
                  } else if (item === '2') {
                    str += '/账号'
                  }
                })
                this.loginMethod = str
              }
            }
          })
        }
      })
    },
    sendCodeClose() {
      this.isLoading = false
      this.configValueStatus = false
      this.isCheckSendCode = false
    },
    sendCodeSuc() {
      this.configValueStatus = false
      this.isCheckSendCode = true
      this.loginSubmit()
    },
    async loginSubmit() {
      if (!this.isAgree) {
        uni.showToast({
          title: '请阅读并勾选底部协议',
          icon: 'none',
          duration: 1000
        })
        return

      }
      let { pwd } = this.loginForm
      let decrypted = encryptPwd(pwd)
      if (this.rememberPassword) {
        // 保存账户信息
        uni.setStorageSync('username', this.loginForm.username)
        uni.setStorageSync('password', pwd)
        uni.setStorageSync('rememberpwd', 1)
      }
      try {
        const loginRes = await uni.login();
        if (loginRes[1].code) {
          console.log('登录凭证 code：', loginRes.code);
          if (this.rememberPassword) {
            uni.setStorageSync('rememberPassword', this.loginForm.pwd)
          }
          let params = {
            code: loginRes[1].code,
            // username: '19124364232',
            username: this.loginForm.username,
            clientId: '',
            verificationCode: null,
            pwd: decrypted,
          }
          let loginRes1 = await this.$Posting(this.$api.loginOrg, params);
          if (!loginRes1.data) {
            if (loginRes1.message && loginRes1.message.includes('密码错误')) {
              this.$u.toast({
                title: '密码错误',
                type: 'error',
              });
            } else if (loginRes1.message && loginRe1s.message.includes('已被冻结')) {
              this.$u.toast({
                title: loginRes1.message,
                type: 'error',
                duration: 3000
              });
            } else {
              this.$u.toast({
                title: loginRes1.message,
                type: 'error',
                duration: 3000
              });
            }
            return
          } else {
            // 修改后的代码
            let setData = {
              XUserToken: loginRes1.data.tokenKey,
              ipAddress: this.$baseURL
            };
            if (loginRes1.data.orgList && loginRes1.data.orgList.length) {
              // 多组织场景
              setData.orgList = loginRes1.data.orgList;
              this.isMultipleOrgUser = true;
            } else {
              // 单组织场景
              setData.XUserToken = loginRes1.data.tokenKey;
              setData.orgInfo = loginRes1.data.orgInfo;
              let { tokenKey, orgInfo, refreshToken } = loginRes1.data || {};
              console.log(tokenKey, 'userToken')
              uni.setStorageSync('XUserToken', tokenKey || '');
              uni.setStorageSync('refreshToken', JSON.stringify(refreshToken));

              this.$store.commit('setAppOrgInfo', orgInfo);

              console.log(orgInfo, 'orginfo')
              await this.$store.dispatch('getAppUserInfo', { orgId: orgInfo.orgId });

              // 获取应用列表
              await this.$store.dispatch('getAppGroupList', { orgId: orgInfo.orgId });
            }

            uni.setStorageSync('appInfo', JSON.stringify(setData));
            uni.setStorageSync('userName', this.loginForm.username);

            // uni.removeStorageSync('iotToken');

            if (this.isMultipleOrgUser) {
              uni.redirectTo({ url: '/pages/login/chooseOrg' });
            } else {
              console.log('跳转了')
              uni.switchTab({ url: '/pages/home/index' });
            }
          }

        } else {
          throw new Error('获取 code 失败：' + loginRes.errMsg);
        }
      } catch (error) {
        console.error('登录异常：', error);
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
      // 登录成功后跳到首页
      //   let a = 0;
      //  if(a){
      //    uni.reLaunch({
      // 						url: '/pages/home/index'
      // 					})
      //  }else{
      //   uni.navigateTo({ url: '/pages/login/choseOrg' })
      //  }

    },
    seeAggrement() {
      this.isShowAgreement = true
    },
    forgotPwdClick() {
      uni.navigateTo({ url: '/pages/forgotPwd/forgotPwd' })
    },
  },
  onUnload() {
    // 清除定时器
    if (this.codeInterval) {
      clearInterval(this.codeInterval)
    }
  }
}
</script>

<style lang="scss" scoped>
// @import '../../styles/global.css';

.login-page {
  height: 100vh;
  width: 100vw;
  min-height: 720rpx;
  position: relative;
  background-color: #f9f9f9;

  .banner-block {
    border-bottom-left-radius: 30rpx;
    border-bottom-right-radius: 30rpx;
    overflow: hidden;

    image {
      width: 100%;
    }
  }
}


.login-main {
  background: #fff;
  margin: 0 auto;
  position: absolute;
  left: 50%;
  width: 700rpx;
  height: 60%;
  top: 92rpx;
  border-radius: 20rpx;
  // margin: 24rpx 24rpx;
  transform: translateX(-50%);

  .server-btn {
    color: #fff;
    position: absolute;
    right: 16rpx;
    top: -36rpx;
    font-size: 24rpx;
    padding-right: 6rpx;

    .arrow-right {
      /* 箭头大小 */
      display: inline-block;
      width: 12rpx;
      height: 12rpx;
      /* 箭头颜色 */
      border-top: 3rpx solid #fff;
      border-right: 3rpx solid #fff;

      /* 旋转角度形成右箭头 */
      transform: rotate(45deg);
      /* 抗锯齿处理 */
      transform-origin: center;
      backface-visibility: hidden;
    }
  }

  .logo {
    width: 100rpx;
    height: 100rpx;
    margin: 0 auto;
    position: relative;
    top: 62rpx;
    background-color: #ffffff;
    border-radius: 4rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }
}

.login-form {
  margin: 0 auto;
  position: relative;
  top: 82rpx;
  margin-top: 86rpx;

  >view {
    position: relative;
    margin-top: 10rpx;
  }

  input {
    width: 600rpx;
    height: 40rpx;
    border-bottom: 1px solid #dae0e5;
    color: #333333;
    font-size: 30rpx;
    line-height: 24rpx;
    padding: 0 40rpx;
    padding-right: 40rpx;
  }

  .form-label {
    display: flex;
    padding-left: 20rpx;
    align-items: center;

    image {
      width: 32rpx;
      margin-right: 5rpx;
      vertical-align: middle;
    }

    .form-label-text {
      display: inline-block;
      padding-left: 12rpx;
      color: #222;
    }
  }
}

.form-item {
  &+.form-item {
    position: relative;
    top: 10rpx;
    padding-top: 30rpx;
  }

  .form-item-content {
    margin-top: 16rpx;
    position: relative;
    // font-size: 16rpx;
  }

  .error {
    color: #EB5757;
    // position: absolute;
    display: block;
    width: 100%;
    font-size: 14px;
    height: 20rpx;
    line-height: 20rpx;
    padding-left: 36rpx;
    bottom: -4rpx;
    transform: translateY(100%);
  }

  .suffix {
    position: absolute;
    top: 50%;
    display: inline-block;
    right: 15rpx;
    transform: translateY(-50%);
    padding: 6rpx 8rpx;

    .close-icon {
      display: inline-block;
      width: 40rpx;
      height: 40rpx;
    }

    image {
      display: inline-block;
      width: 20rpx;
      height: 20rpx;
    }
  }
}

.login-btn {
  height: 50rpx;
  margin: 0 auto;
  margin-top: 200rpx;

  .syswin-button {
    width: 86%;
    color: #fff;
    height: 78rpx;
    border-radius: 10rpx;

    &.primary {
      background: #409EFF;
    }

    &.disabled {
      background: rgba(86, 125, 244, .5);
    }
  }
}

.wuyetoon-agreement {
  width: 100%;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 16rpx;
  bottom: 80rpx;
  font-size: 16rpx;

  .agreement-box {
    margin-right: 5rpx;
    margin-top: -1rpx;
    // width: 10rpx !important;
    // height: 10rpx !important;
    border-radius: 5rpx !important;
  }

  text {
    font-size: 26rpx;
    color: #333333;

    &:last-of-type {
      color: #3395ff;
    }
  }
}

.version {
  font-size: 26rpx;
  text-align: center;
  width: 100%;
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 16rpx;
  bottom: 48rpx;
}

.remember-password {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 6rpx;
}

.options-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  position: relative;
  top: 32rpx;
}

.remember-item {
  display: flex;
  align-items: center;
}

.remember-text {
  font-size: 28rpx;
  color: #409EFF;
  margin-left: 10rpx;
}

.forgotPwd {
  font-size: 28rpx;
  color: #333;
}
</style>